<template>
  <div class="chat-container">
    <div class="chat-box" ref="chatBox">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
        <div class="message-content">{{ message.content }}</div>
      </div>
    </div>
    <div class="input-container">
      <input
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="请输入消息..."
        :disabled="loading"
      />
      <button @click="sendMessage" :disabled="loading || !userInput.trim()">
        {{ loading ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';

const messages = ref([]);
const userInput = ref('');
const loading = ref(false);
const chatBox = ref(null);

const scrollToBottom = async () => {
  await nextTick();
  if (chatBox.value) {
    chatBox.value.scrollTop = chatBox.value.scrollHeight;
  }
};

const sendMessage = async () => {
  const message = userInput.value.trim();
  if (!message || loading.value) return;

  messages.value.push({ role: 'user', content: message });
  userInput.value = '';
  loading.value = true;

  try {
    const response = await fetch('http://localhost:5000/api/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message }),
    });

    const data = await response.json();
    if (response.ok) {
      messages.value.push({ role: 'assistant', content: data.response });
    } else {
      messages.value.push({ role: 'assistant', content: `错误: ${data.error}` });
    }
  } catch (error) {
    messages.value.push({ role: 'assistant', content: `错误: ${error.message}` });
  } finally {
    loading.value = false;
    scrollToBottom();
  }
};

onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 80vh;
}

.chat-box {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.message {
  margin: 10px 0;
  padding: 10px;
  border-radius: 4px;
  max-width: 80%;
}

.message.user {
  background-color: #e3f2fd;
  margin-left: auto;
}

.message.assistant {
  background-color: #f5f5f5;
  margin-right: auto;
}

.message-content {
  word-break: break-word;
}

.input-container {
  display: flex;
  gap: 10px;
}

input {
  flex-grow: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #66b1ff;
}
</style>